<template>
  <div>
    <a-spin :tip="loadTips" :spinning="spinning" size="large">
      <a-list item-layout="horizontal" :data-source="data">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta>
              <template #description>
                <span>{{ item.description }}</span>
                <span v-if="item.value">：{{ item.value }}</span>
              </template>
              <template #title>
                <a>{{ item.title }}</a>
              </template>
            </a-list-item-meta>
            <template #actions>
              <a @click="oauth(item.operate)">绑定/换绑</a>
            </template>
          </a-list-item>
        </template>
      </a-list>
      <a-modal
        v-model:open="wechat_qrcode_visible"
        title="请扫描二维码绑定微信"
        :footer="null"
        width="350px"
      >
        <a-qrcode
          v-if="bindStatus.cd === 0"
          :value="qrcodeUrl"
          :status="qrcodeStatus"
          size="302"
          @refresh="oauth('wechat')"
        />
        <a-result v-if="bindStatus.cd < 0" status="warning" :title="bindStatus.msg" />
        <a-result v-if="bindStatus.cd == 200" status="success" :title="bindStatus.msg" />
      </a-modal>
    </a-spin>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch } from 'vue'
import { getBindingAccount, bindOauth, getWxBindStatus, getWxBindQrcode } from '@/api/personal'
import { useRoute } from 'vue-router'
import { Spin, QRCode, Result } from 'ant-design-vue'

export default defineComponent({
  name: 'BindingSettings',
  components: {
    [QRCode.name]: QRCode,
    [Result.name]: Result,
    [Spin.name]: Spin
  },
  setup() {
    const state = reactive<any>({
      data: [
        {
          title: '微信授权',
          description: '您还未绑定微信授权',
          value: '',
          operate: 'wechat'
        }
        // {
        //   title: '企业微信授权',
        //   description: '您还未绑定企业微信授权',
        //   value: '',
        //   operate: 'wwork'
        // }
      ],
      pageData: {},
      qrcodeStatus: 'active',
      qrcodeNum: 0,
      qrcodeUrl: '',
      bindStatus: {
        cd: 0
      },
      qrToken: '',
      loadTips: '',
      wechat_qrcode_visible: false,
      spinning: false
    })
    watch(
      () => state.wechat_qrcode_visible,
      () => {
        if (state.wechat_qrcode_visible === false) {
          clearInterval(state.interval)
        }
      }
    )
    const route = useRoute()
    if (route.query?.state == 'wx_bind' && route.query.code) {
      state.spinning = true
      state.loadTips = '微信授权绑定中……'
      state.wechatData.code = route.query.code
      state.wechatData.type = 'wx_bind'
      oauthBind(state.wechatData)
    }
    if (route.query?.state == 'ww_bind' && route.query.code) {
      state.spinning = true
      state.loadTips = '企业微信授权绑定中……'
      state.wechatData.code = route.query.code
      state.wechatData.type = 'ww_bind'
      oauthBind(state.wechatData)
    }
    onMounted(() => {
      getDataList()
    })
    function oauthBind(data) {
      bindOauth(data).then(() => {
        state.spinning = false
        getDataList()
      })
    }
    function getDataList() {
      getBindingAccount({}).then((res) => {
        state.pageData = res
        if (res.wechat_nickname) {
          state.data[0].value = res.wechat_nickname
          state.data[0].description = '已绑定微信帐号'
        }
        if (res.ww_user_bind == 1) {
          state.data[1].description = '已绑定企业微信'
        }
      })
    }
    const oauth = (item) => {
      if (item == 'wechat') {
        bindWechat()
      } else if (item == 'wwork') {
        bindWeWork()
      }
    }
    const bindWechat = () => {
      state.wechat_qrcode_visible = true
      getWxBindQrcode()
        .then((res) => {
          state.qrcodeStatus = 'active'
          state.qrcodeUrl = res.url
          state.qrToken = res.token
          wechatbindStatus()
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const wechatbindStatus = () => {
      state.interval = setInterval(() => {
        if (state.qrcodeNum >= 120) {
          state.qrcodeStatus = 'expired'
          clearInterval(state.interval)
        }
        state.qrcodeNum++
        getWxBindStatus()
          .then((res) => {
            state.bindStatus = res
            if (res.cd === 200) {
              clearInterval(state.interval)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }, 1000)
    }
    const bindWeWork = () => {
      state.wechat_qrcode_visible = true
      setTimeout(() => {
        ;(window as any).WwLogin({
          id: 'wechat_qrcode',
          appid: state.pageData?.ww_appid,
          agentid: state.pageData?.ww_agentid,
          redirect_uri: window.location.href,
          state: 'ww_bind',
          href: ''
        })
      }, 300)
    }
    return {
      ...toRefs(state),
      oauth,
      bindWechat,
      bindWeWork
    }
  }
})
</script>

<style lang="scss" scoped></style>
